package com.ebt.m.proposal_v2.widget.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.util.AttributeSet;
import android.widget.Button;

import com.ebt.m.R;
import com.ebt.m.proposal_v2.helper.PickerHelper;
import com.ebt.m.proposal_v2.helper.ThemeHelper;

/**
 * @author archer.qi
 *         Created on 2017/6/7.
 */
public class EnableButton extends Button {

    private boolean isEnableState;
    private String unEnabledMsg;
    private OnClickListener onClickListener;
    private FragmentManager fragmentManager;

    private boolean allowClickAgain = true;
    private Handler flagHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            allowClickAgain = true;
        }
    };

    public EnableButton(Context context) {
        this(context, null);
    }

    public EnableButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EnableButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOnClickListener(v -> {
            if (allowClickAgain) {
                allowClickAgain = false;
                flagHandler.sendEmptyMessageDelayed(0, 500);
                if (isEnableState) {
                    if (onClickListener != null) {
                        onClickListener.onClick(v);
                    }
                } else {
                    PickerHelper.tip(unEnabledMsg).show(fragmentManager, "tip");
                }
            }
        });

    }

    public void setEnableState(boolean enable) {
        isEnableState = enable;
        if (!isEnableState) {
            setBackgroundColor(ThemeHelper.getColor(getContext(), R.color.BackgroundGray));
        } else {
            setBackgroundResource(R.drawable.selector_btn_orange);
        }
    }

    /**
     * 状态为UnEnabled时，点击提示的文本
     *
     * @param msg
     */
    public void setUnEnabledMessage(String msg) {
        unEnabledMsg = msg;
    }

    public void setClickListener(OnClickListener listener) {
        onClickListener = listener;
    }

    public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }


}
